{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "1a4596ea-a631-416d-a2a4-3577c140493d",
   "metadata": {
    "tags": []
   },
   "source": [
    "# LangSmith Walkthrough\n",
    "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/langchain-ai/langchain/blob/master/docs/docs/langsmith/walkthrough.ipynb)\n",
    "\n",
    "LangChain makes it easy to prototype LLM applications and Agents. However, delivering LLM applications to production can be deceptively difficult. You will have to iterate on your prompts, chains, and other components to build a high-quality product.\n",
    "\n",
    "LangSmith makes it easy to debug, test, and continuously improve your LLM applications.\n",
    "\n",
    "When might this come in handy? You may find it useful when you want to:\n",
    "\n",
    "- Quickly debug a new chain, agent, or set of tools\n",
    "- Create and manage datasets for fine-tuning, few-shot prompting, and evaluation\n",
    "- Run regression tests on your application to confidently develop\n",
    "- Capture production analytics for product insights and continuous improvements"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "138fbb8f-960d-4d26-9dd5-6d6acab3ee55",
   "metadata": {},
   "source": [
    "## Prerequisites\n",
    "\n",
    "**[Create a LangSmith account](https://smith.langchain.com/) and create an API key (see bottom left corner). Familiarize yourself with the platform by looking through the [docs](https://docs.smith.langchain.com/)**\n",
    "\n",
    "Note LangSmith is in closed beta; we're in the process of rolling it out to more users. However, you can fill out the form on the website for expedited access.\n",
    "\n",
    "Now, let's get started!"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2d77d064-41b4-41fb-82e6-2d16461269ec",
   "metadata": {
    "tags": []
   },
   "source": [
    "## Log runs to LangSmith\n",
    "\n",
    "First, configure your environment variables to tell LangChain to log traces. This is done by setting the `LANGCHAIN_TRACING_V2` environment variable to true.\n",
    "You can tell LangChain which project to log to by setting the `LANGCHAIN_PROJECT` environment variable (if this isn't set, runs will be logged to the `default` project). This will automatically create the project for you if it doesn't exist. You must also set the `LANGCHAIN_ENDPOINT` and `LANGCHAIN_API_KEY` environment variables.\n",
    "\n",
    "For more information on other ways to set up tracing, please reference the [LangSmith documentation](https://docs.smith.langchain.com/docs/).\n",
    "\n",
    "**NOTE:** You can also use a context manager in python to log traces using\n",
    "\n",
    "```python\n",
    "from langchain_core.tracers.context import tracing_v2_enabled\n",
    "\n",
    "with tracing_v2_enabled(project_name=\"My Project\"):\n",
    "    agent.run(\"How many people live in canada as of 2023?\")\n",
    "```\n",
    "\n",
    "However, in this example, we will use environment variables."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e4780363-f05a-4649-8b1a-9b449f960ce4",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install --upgrade --quiet  langchain langsmith langchainhub --quiet\n",
    "%pip install --upgrade --quiet  langchain-openai tiktoken pandas duckduckgo-search --quiet"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "904db9a5-f387-4a57-914c-c8af8d39e249",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "import os\n",
    "from uuid import uuid4\n",
    "\n",
    "unique_id = uuid4().hex[0:8]\n",
    "os.environ[\"LANGCHAIN_TRACING_V2\"] = \"true\"\n",
    "os.environ[\"LANGCHAIN_PROJECT\"] = f\"Tracing Walkthrough - {unique_id}\"\n",
    "os.environ[\"LANGCHAIN_ENDPOINT\"] = \"https://api.smith.langchain.com\"\n",
    "os.environ[\"LANGCHAIN_API_KEY\"] = \"<YOUR-API-KEY>\"  # Update to your API key\n",
    "\n",
    "# Used by the agent in this tutorial\n",
    "os.environ[\"OPENAI_API_KEY\"] = \"<YOUR-OPENAI-API-KEY>\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8ee7f34b-b65c-4e09-ad52-e3ace78d0221",
   "metadata": {
    "tags": []
   },
   "source": [
    "Create the langsmith client to interact with the API"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "510b5ca0",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "from langsmith import Client\n",
    "\n",
    "client = Client()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ca27fa11-ddce-4af0-971e-c5c37d5b92ef",
   "metadata": {},
   "source": [
    "Create a LangChain component and log runs to the platform. In this example, we will create a ReAct-style agent with access to a general search tool (DuckDuckGo). The agent's prompt can be viewed in the [Hub here](https://smith.langchain.com/hub/wfh/langsmith-agent-prompt)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "a0fbfbba-3c82-4298-a312-9cec016d9d2e",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain import hub\n",
    "from langchain.agents import AgentExecutor\n",
    "from langchain.agents.format_scratchpad import format_to_openai_function_messages\n",
    "from langchain.agents.output_parsers import OpenAIFunctionsAgentOutputParser\n",
    "from langchain_community.tools import DuckDuckGoSearchResults\n",
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "# Fetches the latest version of this prompt\n",
    "prompt = hub.pull(\"wfh/langsmith-agent-prompt:5d466cbc\")\n",
    "\n",
    "llm = ChatOpenAI(\n",
    "    model=\"gpt-3.5-turbo-16k\",\n",
    "    temperature=0,\n",
    ")\n",
    "\n",
    "tools = [\n",
    "    DuckDuckGoSearchResults(\n",
    "        name=\"duck_duck_go\"\n",
    "    ),  # General internet search using DuckDuckGo\n",
    "]\n",
    "\n",
    "llm_with_tools = llm.bind_functions(tools)\n",
    "\n",
    "runnable_agent = (\n",
    "    {\n",
    "        \"input\": lambda x: x[\"input\"],\n",
    "        \"agent_scratchpad\": lambda x: format_to_openai_function_messages(\n",
    "            x[\"intermediate_steps\"]\n",
    "        ),\n",
    "    }\n",
    "    | prompt\n",
    "    | llm_with_tools\n",
    "    | OpenAIFunctionsAgentOutputParser()\n",
    ")\n",
    "\n",
    "agent_executor = AgentExecutor(\n",
    "    agent=runnable_agent, tools=tools, handle_parsing_errors=True\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cab51e1e-8270-452c-ba22-22b5b5951899",
   "metadata": {},
   "source": [
    "We are running the agent concurrently on multiple inputs to reduce latency. Runs get logged to LangSmith in the background so execution latency is unaffected."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "19537902-b95c-4390-80a4-f6c9a937081e",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "inputs = [\n",
    "    \"What is LangChain?\",\n",
    "    \"What's LangSmith?\",\n",
    "    \"When was Llama-v2 released?\",\n",
    "    \"What is the langsmith cookbook?\",\n",
    "    \"When did langchain first announce the hub?\",\n",
    "]\n",
    "\n",
    "results = agent_executor.batch([{\"input\": x} for x in inputs], return_exceptions=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "9a6a764c-5d7a-4de7-a916-3ecc987d5bb6",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[{'input': 'What is LangChain?',\n",
       "  'output': 'I\\'m sorry, but I couldn\\'t find any information about \"LangChain\". Could you please provide more context or clarify your question?'},\n",
       " {'input': \"What's LangSmith?\",\n",
       "  'output': 'I\\'m sorry, but I couldn\\'t find any information about \"LangSmith\". It could be a company, a product, or a person. Can you provide more context or details about what you are referring to?'}]"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "results[:2]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9decb964-be07-4b6c-9802-9825c8be7b64",
   "metadata": {},
   "source": [
    "Assuming you've successfully set up your environment, your agent traces should show up in the `Projects` section in the [app](https://smith.langchain.com/). Congrats!\n",
    "\n",
    "![Initial Runs](./img/log_traces.png)\n",
    "\n",
    "It looks like the agent isn't effectively using the tools though. Let's evaluate this so we have a baseline."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6c43c311-4e09-4d57-9ef3-13afb96ff430",
   "metadata": {},
   "source": [
    "## Evaluate Agent\n",
    "\n",
    "In addition to logging runs, LangSmith also allows you to test and evaluate your LLM applications.\n",
    "\n",
    "In this section, you will leverage LangSmith to create a benchmark dataset and run AI-assisted evaluators on an agent. You will do so in a few steps:\n",
    "\n",
    "1. Create a dataset\n",
    "2. Initialize a new agent to benchmark\n",
    "3. Configure evaluators to grade an agent's output\n",
    "4. Run the agent over the dataset and evaluate the results"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "beab1a29-b79d-4a99-b5b1-0870c2d772b1",
   "metadata": {},
   "source": [
    "### 1. Create a LangSmith dataset\n",
    "\n",
    "Below, we use the LangSmith client to create a dataset from the input questions from above and a list labels. You will use these later to measure performance for a new agent. A dataset is a collection of examples, which are nothing more than input-output pairs you can use as test cases to your application.\n",
    "\n",
    "For more information on datasets, including how to create them from CSVs or other files or how to create them in the platform, please refer to the [LangSmith documentation](https://docs.smith.langchain.com/)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "43fd40b2-3f02-4e51-9343-705aafe90a36",
   "metadata": {},
   "outputs": [],
   "source": [
    "outputs = [\n",
    "    \"LangChain is an open-source framework for building applications using large language models. It is also the name of the company building LangSmith.\",\n",
    "    \"LangSmith is a unified platform for debugging, testing, and monitoring language model applications and agents powered by LangChain\",\n",
    "    \"July 18, 2023\",\n",
    "    \"The langsmith cookbook is a github repository containing detailed examples of how to use LangSmith to debug, evaluate, and monitor large language model-powered applications.\",\n",
    "    \"September 5, 2023\",\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "17580c4b-bd04-4dde-9d21-9d4edd25b00d",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "dataset_name = f\"agent-qa-{unique_id}\"\n",
    "\n",
    "dataset = client.create_dataset(\n",
    "    dataset_name,\n",
    "    description=\"An example dataset of questions over the LangSmith documentation.\",\n",
    ")\n",
    "\n",
    "client.create_examples(\n",
    "    inputs=[{\"input\": query} for query in inputs],\n",
    "    outputs=[{\"output\": answer} for answer in outputs],\n",
    "    dataset_id=dataset.id,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8adfd29c-b258-49e5-94b4-74597a12ba16",
   "metadata": {
    "tags": []
   },
   "source": [
    "### 2. Initialize a new agent to benchmark\n",
    "\n",
    "LangSmith lets you evaluate any LLM, chain, agent, or even a custom function. Conversational agents are stateful (they have memory); to ensure that this state isn't shared between dataset runs, we will pass in a `chain_factory` (aka a `constructor`) function to initialize for each call.\n",
    "\n",
    "In this case, we will test an agent that uses OpenAI's function calling endpoints."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "f42d8ecc-d46a-448b-a89c-04b0f6907f75",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "from langchain import hub\n",
    "from langchain.agents import AgentExecutor, AgentType, initialize_agent, load_tools\n",
    "from langchain.agents.format_scratchpad import format_to_openai_function_messages\n",
    "from langchain.agents.output_parsers import OpenAIFunctionsAgentOutputParser\n",
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "\n",
    "# Since chains can be stateful (e.g. they can have memory), we provide\n",
    "# a way to initialize a new chain for each row in the dataset. This is done\n",
    "# by passing in a factory function that returns a new chain for each row.\n",
    "def create_agent(prompt, llm_with_tools):\n",
    "    runnable_agent = (\n",
    "        {\n",
    "            \"input\": lambda x: x[\"input\"],\n",
    "            \"agent_scratchpad\": lambda x: format_to_openai_function_messages(\n",
    "                x[\"intermediate_steps\"]\n",
    "            ),\n",
    "        }\n",
    "        | prompt\n",
    "        | llm_with_tools\n",
    "        | OpenAIFunctionsAgentOutputParser()\n",
    "    )\n",
    "    return AgentExecutor(agent=runnable_agent, tools=tools, handle_parsing_errors=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9cb9ef53",
   "metadata": {},
   "source": [
    "### 3. Configure evaluation\n",
    "\n",
    "Manually comparing the results of chains in the UI is effective, but it can be time consuming.\n",
    "It can be helpful to use automated metrics and AI-assisted feedback to evaluate your component's performance.\n",
    "\n",
    "Below, we will create a custom run evaluator that logs a heuristic evaluation.\n",
    "\n",
    "**Heuristic evaluators**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "331c3c53-949d-405e-8ba5-38bab1ce413b",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langsmith.evaluation import EvaluationResult, run_evaluator\n",
    "from langsmith.schemas import Example, Run\n",
    "\n",
    "\n",
    "@run_evaluator\n",
    "def check_not_idk(run: Run, example: Example):\n",
    "    \"\"\"Illustration of a custom evaluator.\"\"\"\n",
    "    agent_response = run.outputs[\"output\"]\n",
    "    if \"don't know\" in agent_response or \"not sure\" in agent_response:\n",
    "        score = 0\n",
    "    else:\n",
    "        score = 1\n",
    "    # You can access the dataset labels in example.outputs[key]\n",
    "    # You can also access the model inputs in run.inputs[key]\n",
    "    return EvaluationResult(\n",
    "        key=\"not_uncertain\",\n",
    "        score=score,\n",
    "    )"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ad9c4791-570b-4adf-a23f-d025ff383254",
   "metadata": {},
   "source": [
    "Below, we will configure the evaluation with the custom evaluator from above, as well as some pre-implemented run evaluators that do the following:\n",
    "- Compare results against ground truth labels.\n",
    "- Measure semantic (dis)similarity using embedding distance\n",
    "- Evaluate 'aspects' of the agent's response in a reference-free manner using custom criteria\n",
    "\n",
    "For a longer discussion of how to select an appropriate evaluator for your use case and how to create your own\n",
    "custom evaluators, please refer to the [LangSmith documentation](https://docs.smith.langchain.com/)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "a25dc281",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "from langchain.evaluation import EvaluatorType\n",
    "from langchain.smith import RunEvalConfig\n",
    "\n",
    "evaluation_config = RunEvalConfig(\n",
    "    # Evaluators can either be an evaluator type (e.g., \"qa\", \"criteria\", \"embedding_distance\", etc.) or a configuration for that evaluator\n",
    "    evaluators=[\n",
    "        # Measures whether a QA response is \"Correct\", based on a reference answer\n",
    "        # You can also select via the raw string \"qa\"\n",
    "        EvaluatorType.QA,\n",
    "        # Measure the embedding distance between the output and the reference answer\n",
    "        # Equivalent to: EvalConfig.EmbeddingDistance(embeddings=OpenAIEmbeddings())\n",
    "        EvaluatorType.EMBEDDING_DISTANCE,\n",
    "        # Grade whether the output satisfies the stated criteria.\n",
    "        # You can select a default one such as \"helpfulness\" or provide your own.\n",
    "        RunEvalConfig.LabeledCriteria(\"helpfulness\"),\n",
    "        # The LabeledScoreString evaluator outputs a score on a scale from 1-10.\n",
    "        # You can use default criteria or write our own rubric\n",
    "        RunEvalConfig.LabeledScoreString(\n",
    "            {\n",
    "                \"accuracy\": \"\"\"\n",
    "Score 1: The answer is completely unrelated to the reference.\n",
    "Score 3: The answer has minor relevance but does not align with the reference.\n",
    "Score 5: The answer has moderate relevance but contains inaccuracies.\n",
    "Score 7: The answer aligns with the reference but has minor errors or omissions.\n",
    "Score 10: The answer is completely accurate and aligns perfectly with the reference.\"\"\"\n",
    "            },\n",
    "            normalize_by=10,\n",
    "        ),\n",
    "    ],\n",
    "    # You can add custom StringEvaluator or RunEvaluator objects here as well, which will automatically be\n",
    "    # applied to each prediction. Check out the docs for examples.\n",
    "    custom_evaluators=[check_not_idk],\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "07885b10",
   "metadata": {
    "tags": []
   },
   "source": [
    "### 4. Run the agent and evaluators\n",
    "\n",
    "Use the [run_on_dataset](https://api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.runner_utils.run_on_dataset.html#langchain.smith.evaluation.runner_utils.run_on_dataset) (or asynchronous [arun_on_dataset](https://api.python.langchain.com/en/latest/smith/langchain.smith.evaluation.runner_utils.arun_on_dataset.html#langchain.smith.evaluation.runner_utils.arun_on_dataset)) function to evaluate your model. This will:\n",
    "1. Fetch example rows from the specified dataset.\n",
    "2. Run your agent (or any custom function) on each example.\n",
    "3. Apply evaluators to the resulting run traces and corresponding reference examples to generate automated feedback.\n",
    "\n",
    "The results will be visible in the LangSmith app."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "af8c8469-d70d-46d9-8fcd-517a1ccc7c4b",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain import hub\n",
    "\n",
    "# We will test this version of the prompt\n",
    "prompt = hub.pull(\"wfh/langsmith-agent-prompt:798e7324\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "3733269b-8085-4644-9d5d-baedcff13a2f",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "View the evaluation results for project 'runnable-agent-test-5d466cbc-97e1' at:\n",
      "https://smith.langchain.com/o/ebbaf2eb-769b-4505-aca2-d11de10372a4/datasets/14d8a382-3c0f-48e7-b212-33489ee8a13e/compare?selectedSessions=62f0a0c0-73bf-420c-a907-2c6b2f4625c4\n",
      "\n",
      "View all tests for Dataset agent-qa-e2d24144 at:\n",
      "https://smith.langchain.com/o/ebbaf2eb-769b-4505-aca2-d11de10372a4/datasets/14d8a382-3c0f-48e7-b212-33489ee8a13e\n",
      "[>                                                 ] 0/5"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Server error caused failure to patch https://api.smith.langchain.com/runs/e9d26fe6-bf4a-4f88-81c5-f5d0f70977f0 in LangSmith API. HTTPError('500 Server Error: Internal Server Error for url: https://api.smith.langchain.com/runs/e9d26fe6-bf4a-4f88-81c5-f5d0f70977f0', '{\"detail\":\"Internal server error\"}')\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[------------------------------------------------->] 5/5"
     ]
    },
    {
     "data": {
      "text/html": [
       "<h3>Experiment Results:</h3>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>feedback.correctness</th>\n",
       "      <th>feedback.embedding_cosine_distance</th>\n",
       "      <th>feedback.helpfulness</th>\n",
       "      <th>feedback.score_string:accuracy</th>\n",
       "      <th>feedback.not_uncertain</th>\n",
       "      <th>error</th>\n",
       "      <th>execution_time</th>\n",
       "      <th>run_id</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>count</th>\n",
       "      <td>5.000000</td>\n",
       "      <td>5.000000</td>\n",
       "      <td>5.000000</td>\n",
       "      <td>5.000000</td>\n",
       "      <td>5.0</td>\n",
       "      <td>0</td>\n",
       "      <td>5.000000</td>\n",
       "      <td>5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>unique</th>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>0</td>\n",
       "      <td>NaN</td>\n",
       "      <td>5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>top</th>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>e9440e33-e2c6-4bec-a190-2fa41947e9c5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>freq</th>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>mean</th>\n",
       "      <td>0.800000</td>\n",
       "      <td>0.110268</td>\n",
       "      <td>0.800000</td>\n",
       "      <td>0.640000</td>\n",
       "      <td>1.0</td>\n",
       "      <td>NaN</td>\n",
       "      <td>6.338926</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>std</th>\n",
       "      <td>0.447214</td>\n",
       "      <td>0.060680</td>\n",
       "      <td>0.447214</td>\n",
       "      <td>0.328634</td>\n",
       "      <td>0.0</td>\n",
       "      <td>NaN</td>\n",
       "      <td>2.525439</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>min</th>\n",
       "      <td>0.000000</td>\n",
       "      <td>0.049442</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>0.100000</td>\n",
       "      <td>1.0</td>\n",
       "      <td>NaN</td>\n",
       "      <td>3.858924</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>25%</th>\n",
       "      <td>1.000000</td>\n",
       "      <td>0.064186</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>0.700000</td>\n",
       "      <td>1.0</td>\n",
       "      <td>NaN</td>\n",
       "      <td>5.250572</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>50%</th>\n",
       "      <td>1.000000</td>\n",
       "      <td>0.092256</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>0.700000</td>\n",
       "      <td>1.0</td>\n",
       "      <td>NaN</td>\n",
       "      <td>5.817807</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>75%</th>\n",
       "      <td>1.000000</td>\n",
       "      <td>0.153003</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>0.700000</td>\n",
       "      <td>1.0</td>\n",
       "      <td>NaN</td>\n",
       "      <td>6.199289</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>max</th>\n",
       "      <td>1.000000</td>\n",
       "      <td>0.192453</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>1.0</td>\n",
       "      <td>NaN</td>\n",
       "      <td>10.568036</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "        feedback.correctness  feedback.embedding_cosine_distance  \\\n",
       "count               5.000000                            5.000000   \n",
       "unique                   NaN                                 NaN   \n",
       "top                      NaN                                 NaN   \n",
       "freq                     NaN                                 NaN   \n",
       "mean                0.800000                            0.110268   \n",
       "std                 0.447214                            0.060680   \n",
       "min                 0.000000                            0.049442   \n",
       "25%                 1.000000                            0.064186   \n",
       "50%                 1.000000                            0.092256   \n",
       "75%                 1.000000                            0.153003   \n",
       "max                 1.000000                            0.192453   \n",
       "\n",
       "        feedback.helpfulness  feedback.score_string:accuracy  \\\n",
       "count               5.000000                        5.000000   \n",
       "unique                   NaN                             NaN   \n",
       "top                      NaN                             NaN   \n",
       "freq                     NaN                             NaN   \n",
       "mean                0.800000                        0.640000   \n",
       "std                 0.447214                        0.328634   \n",
       "min                 0.000000                        0.100000   \n",
       "25%                 1.000000                        0.700000   \n",
       "50%                 1.000000                        0.700000   \n",
       "75%                 1.000000                        0.700000   \n",
       "max                 1.000000                        1.000000   \n",
       "\n",
       "        feedback.not_uncertain error  execution_time  \\\n",
       "count                      5.0     0        5.000000   \n",
       "unique                     NaN     0             NaN   \n",
       "top                        NaN   NaN             NaN   \n",
       "freq                       NaN   NaN             NaN   \n",
       "mean                       1.0   NaN        6.338926   \n",
       "std                        0.0   NaN        2.525439   \n",
       "min                        1.0   NaN        3.858924   \n",
       "25%                        1.0   NaN        5.250572   \n",
       "50%                        1.0   NaN        5.817807   \n",
       "75%                        1.0   NaN        6.199289   \n",
       "max                        1.0   NaN       10.568036   \n",
       "\n",
       "                                      run_id  \n",
       "count                                      5  \n",
       "unique                                     5  \n",
       "top     e9440e33-e2c6-4bec-a190-2fa41947e9c5  \n",
       "freq                                       1  \n",
       "mean                                     NaN  \n",
       "std                                      NaN  \n",
       "min                                      NaN  \n",
       "25%                                      NaN  \n",
       "50%                                      NaN  \n",
       "75%                                      NaN  \n",
       "max                                      NaN  "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "import functools\n",
    "\n",
    "from langchain.smith import arun_on_dataset, run_on_dataset\n",
    "\n",
    "chain_results = run_on_dataset(\n",
    "    dataset_name=dataset_name,\n",
    "    llm_or_chain_factory=functools.partial(\n",
    "        create_agent, prompt=prompt, llm_with_tools=llm_with_tools\n",
    "    ),\n",
    "    evaluation=evaluation_config,\n",
    "    verbose=True,\n",
    "    client=client,\n",
    "    project_name=f\"runnable-agent-test-5d466cbc-{unique_id}\",\n",
    "    # Project metadata communicates the experiment parameters,\n",
    "    # Useful for reviewing the test results\n",
    "    project_metadata={\n",
    "        \"env\": \"testing-notebook\",\n",
    "        \"model\": \"gpt-3.5-turbo\",\n",
    "        \"prompt\": \"5d466cbc\",\n",
    "    },\n",
    ")\n",
    "\n",
    "# Sometimes, the agent will error due to parsing issues, incompatible tool inputs, etc.\n",
    "# These are logged as warnings here and captured as errors in the tracing UI."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cdacd159-eb4d-49e9-bb2a-c55322c40ed4",
   "metadata": {
    "tags": []
   },
   "source": [
    "### Review the test results\n",
    "\n",
    "You can review the test results tracing UI below by clicking the URL in the output above or navigating to the \"Testing & Datasets\" page in LangSmith  **\"agent-qa-{unique_id}\"** dataset. \n",
    "\n",
    "![test results](./img/test_results.png)\n",
    "\n",
    "This will show the new runs and the feedback logged from the selected evaluators. You can also explore a summary of the results in tabular format below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "id": "9da60638-5be8-4b5f-a721-2c6627aeaf0c",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>inputs.input</th>\n",
       "      <th>outputs.input</th>\n",
       "      <th>outputs.output</th>\n",
       "      <th>reference.output</th>\n",
       "      <th>feedback.correctness</th>\n",
       "      <th>feedback.embedding_cosine_distance</th>\n",
       "      <th>feedback.helpfulness</th>\n",
       "      <th>feedback.score_string:accuracy</th>\n",
       "      <th>feedback.not_uncertain</th>\n",
       "      <th>error</th>\n",
       "      <th>execution_time</th>\n",
       "      <th>run_id</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>63e7ff81-b3f6-40aa-81c8-3600c504d54f</th>\n",
       "      <td>When did langchain first announce the hub?</td>\n",
       "      <td>When did langchain first announce the hub?</td>\n",
       "      <td>LangChain first announced the LangChain Hub on...</td>\n",
       "      <td>September 5, 2023</td>\n",
       "      <td>1</td>\n",
       "      <td>0.153003</td>\n",
       "      <td>1</td>\n",
       "      <td>1.0</td>\n",
       "      <td>1</td>\n",
       "      <td>None</td>\n",
       "      <td>5.250572</td>\n",
       "      <td>e9440e33-e2c6-4bec-a190-2fa41947e9c5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>48c2b719-93a3-47cb-baa6-ee93ecb1ba30</th>\n",
       "      <td>What is the langsmith cookbook?</td>\n",
       "      <td>What is the langsmith cookbook?</td>\n",
       "      <td>The LangSmith Cookbook is a collection of reci...</td>\n",
       "      <td>The langsmith cookbook is a github repository ...</td>\n",
       "      <td>1</td>\n",
       "      <td>0.049442</td>\n",
       "      <td>1</td>\n",
       "      <td>0.7</td>\n",
       "      <td>1</td>\n",
       "      <td>None</td>\n",
       "      <td>10.568036</td>\n",
       "      <td>ad1d3050-dffb-45a2-ab9d-bbc88a702682</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>96ed16c3-cbc6-4ebb-a335-ec70e64db109</th>\n",
       "      <td>When was Llama-v2 released?</td>\n",
       "      <td>When was Llama-v2 released?</td>\n",
       "      <td>Llama-v2 was released in 2023.</td>\n",
       "      <td>July 18, 2023</td>\n",
       "      <td>1</td>\n",
       "      <td>0.192453</td>\n",
       "      <td>1</td>\n",
       "      <td>0.7</td>\n",
       "      <td>1</td>\n",
       "      <td>None</td>\n",
       "      <td>6.199289</td>\n",
       "      <td>646518d4-b4be-4b20-b5cb-9b86e0a8fe86</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7342bb9c-9733-47bd-b88e-cd4ab4f4f82d</th>\n",
       "      <td>What's LangSmith?</td>\n",
       "      <td>What's LangSmith?</td>\n",
       "      <td>LangSmith is a platform that helps developers ...</td>\n",
       "      <td>LangSmith is a unified platform for debugging,...</td>\n",
       "      <td>1</td>\n",
       "      <td>0.064186</td>\n",
       "      <td>1</td>\n",
       "      <td>0.7</td>\n",
       "      <td>1</td>\n",
       "      <td>None</td>\n",
       "      <td>5.817807</td>\n",
       "      <td>07d157f1-a18c-4173-bda0-1b3ac8d8dcf2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>aee03fdf-c63e-4f63-9075-a90be3922c7f</th>\n",
       "      <td>What is LangChain?</td>\n",
       "      <td>What is LangChain?</td>\n",
       "      <td>LangChain is a decentralized blockchain platfo...</td>\n",
       "      <td>LangChain is an open-source framework for buil...</td>\n",
       "      <td>0</td>\n",
       "      <td>0.092256</td>\n",
       "      <td>0</td>\n",
       "      <td>0.1</td>\n",
       "      <td>1</td>\n",
       "      <td>None</td>\n",
       "      <td>3.858924</td>\n",
       "      <td>bf1bc257-2ab6-464e-b6d1-99f25b042383</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                                                                    inputs.input  \\\n",
       "63e7ff81-b3f6-40aa-81c8-3600c504d54f  When did langchain first announce the hub?   \n",
       "48c2b719-93a3-47cb-baa6-ee93ecb1ba30             What is the langsmith cookbook?   \n",
       "96ed16c3-cbc6-4ebb-a335-ec70e64db109                 When was Llama-v2 released?   \n",
       "7342bb9c-9733-47bd-b88e-cd4ab4f4f82d                           What's LangSmith?   \n",
       "aee03fdf-c63e-4f63-9075-a90be3922c7f                          What is LangChain?   \n",
       "\n",
       "                                                                   outputs.input  \\\n",
       "63e7ff81-b3f6-40aa-81c8-3600c504d54f  When did langchain first announce the hub?   \n",
       "48c2b719-93a3-47cb-baa6-ee93ecb1ba30             What is the langsmith cookbook?   \n",
       "96ed16c3-cbc6-4ebb-a335-ec70e64db109                 When was Llama-v2 released?   \n",
       "7342bb9c-9733-47bd-b88e-cd4ab4f4f82d                           What's LangSmith?   \n",
       "aee03fdf-c63e-4f63-9075-a90be3922c7f                          What is LangChain?   \n",
       "\n",
       "                                                                         outputs.output  \\\n",
       "63e7ff81-b3f6-40aa-81c8-3600c504d54f  LangChain first announced the LangChain Hub on...   \n",
       "48c2b719-93a3-47cb-baa6-ee93ecb1ba30  The LangSmith Cookbook is a collection of reci...   \n",
       "96ed16c3-cbc6-4ebb-a335-ec70e64db109                     Llama-v2 was released in 2023.   \n",
       "7342bb9c-9733-47bd-b88e-cd4ab4f4f82d  LangSmith is a platform that helps developers ...   \n",
       "aee03fdf-c63e-4f63-9075-a90be3922c7f  LangChain is a decentralized blockchain platfo...   \n",
       "\n",
       "                                                                       reference.output  \\\n",
       "63e7ff81-b3f6-40aa-81c8-3600c504d54f                                  September 5, 2023   \n",
       "48c2b719-93a3-47cb-baa6-ee93ecb1ba30  The langsmith cookbook is a github repository ...   \n",
       "96ed16c3-cbc6-4ebb-a335-ec70e64db109                                      July 18, 2023   \n",
       "7342bb9c-9733-47bd-b88e-cd4ab4f4f82d  LangSmith is a unified platform for debugging,...   \n",
       "aee03fdf-c63e-4f63-9075-a90be3922c7f  LangChain is an open-source framework for buil...   \n",
       "\n",
       "                                      feedback.correctness  \\\n",
       "63e7ff81-b3f6-40aa-81c8-3600c504d54f                     1   \n",
       "48c2b719-93a3-47cb-baa6-ee93ecb1ba30                     1   \n",
       "96ed16c3-cbc6-4ebb-a335-ec70e64db109                     1   \n",
       "7342bb9c-9733-47bd-b88e-cd4ab4f4f82d                     1   \n",
       "aee03fdf-c63e-4f63-9075-a90be3922c7f                     0   \n",
       "\n",
       "                                      feedback.embedding_cosine_distance  \\\n",
       "63e7ff81-b3f6-40aa-81c8-3600c504d54f                            0.153003   \n",
       "48c2b719-93a3-47cb-baa6-ee93ecb1ba30                            0.049442   \n",
       "96ed16c3-cbc6-4ebb-a335-ec70e64db109                            0.192453   \n",
       "7342bb9c-9733-47bd-b88e-cd4ab4f4f82d                            0.064186   \n",
       "aee03fdf-c63e-4f63-9075-a90be3922c7f                            0.092256   \n",
       "\n",
       "                                      feedback.helpfulness  \\\n",
       "63e7ff81-b3f6-40aa-81c8-3600c504d54f                     1   \n",
       "48c2b719-93a3-47cb-baa6-ee93ecb1ba30                     1   \n",
       "96ed16c3-cbc6-4ebb-a335-ec70e64db109                     1   \n",
       "7342bb9c-9733-47bd-b88e-cd4ab4f4f82d                     1   \n",
       "aee03fdf-c63e-4f63-9075-a90be3922c7f                     0   \n",
       "\n",
       "                                      feedback.score_string:accuracy  \\\n",
       "63e7ff81-b3f6-40aa-81c8-3600c504d54f                             1.0   \n",
       "48c2b719-93a3-47cb-baa6-ee93ecb1ba30                             0.7   \n",
       "96ed16c3-cbc6-4ebb-a335-ec70e64db109                             0.7   \n",
       "7342bb9c-9733-47bd-b88e-cd4ab4f4f82d                             0.7   \n",
       "aee03fdf-c63e-4f63-9075-a90be3922c7f                             0.1   \n",
       "\n",
       "                                      feedback.not_uncertain error  \\\n",
       "63e7ff81-b3f6-40aa-81c8-3600c504d54f                       1  None   \n",
       "48c2b719-93a3-47cb-baa6-ee93ecb1ba30                       1  None   \n",
       "96ed16c3-cbc6-4ebb-a335-ec70e64db109                       1  None   \n",
       "7342bb9c-9733-47bd-b88e-cd4ab4f4f82d                       1  None   \n",
       "aee03fdf-c63e-4f63-9075-a90be3922c7f                       1  None   \n",
       "\n",
       "                                      execution_time  \\\n",
       "63e7ff81-b3f6-40aa-81c8-3600c504d54f        5.250572   \n",
       "48c2b719-93a3-47cb-baa6-ee93ecb1ba30       10.568036   \n",
       "96ed16c3-cbc6-4ebb-a335-ec70e64db109        6.199289   \n",
       "7342bb9c-9733-47bd-b88e-cd4ab4f4f82d        5.817807   \n",
       "aee03fdf-c63e-4f63-9075-a90be3922c7f        3.858924   \n",
       "\n",
       "                                                                    run_id  \n",
       "63e7ff81-b3f6-40aa-81c8-3600c504d54f  e9440e33-e2c6-4bec-a190-2fa41947e9c5  \n",
       "48c2b719-93a3-47cb-baa6-ee93ecb1ba30  ad1d3050-dffb-45a2-ab9d-bbc88a702682  \n",
       "96ed16c3-cbc6-4ebb-a335-ec70e64db109  646518d4-b4be-4b20-b5cb-9b86e0a8fe86  \n",
       "7342bb9c-9733-47bd-b88e-cd4ab4f4f82d  07d157f1-a18c-4173-bda0-1b3ac8d8dcf2  \n",
       "aee03fdf-c63e-4f63-9075-a90be3922c7f  bf1bc257-2ab6-464e-b6d1-99f25b042383  "
      ]
     },
     "execution_count": 34,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "chain_results.to_dataframe()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "13aad317-73ff-46a7-a5a0-60b5b5295f02",
   "metadata": {},
   "source": [
    "### (Optional) Compare to another prompt\n",
    "\n",
    "Now that we have our test run results, we can make changes to our agent and benchmark them. Let's try this again with a different prompt and see the results."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "5eeb023f-ded2-4d0f-b910-2a57d9675853",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "View the evaluation results for project 'runnable-agent-test-39f3bbd0-97e1' at:\n",
      "https://smith.langchain.com/o/ebbaf2eb-769b-4505-aca2-d11de10372a4/datasets/14d8a382-3c0f-48e7-b212-33489ee8a13e/compare?selectedSessions=7753a05e-8235-4bc2-a227-d0622c1a36a4\n",
      "\n",
      "View all tests for Dataset agent-qa-e2d24144 at:\n",
      "https://smith.langchain.com/o/ebbaf2eb-769b-4505-aca2-d11de10372a4/datasets/14d8a382-3c0f-48e7-b212-33489ee8a13e\n",
      "[------------------------------------------------->] 5/5"
     ]
    },
    {
     "data": {
      "text/html": [
       "<h3>Experiment Results:</h3>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>feedback.correctness</th>\n",
       "      <th>feedback.embedding_cosine_distance</th>\n",
       "      <th>feedback.helpfulness</th>\n",
       "      <th>feedback.score_string:accuracy</th>\n",
       "      <th>feedback.not_uncertain</th>\n",
       "      <th>error</th>\n",
       "      <th>execution_time</th>\n",
       "      <th>run_id</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>count</th>\n",
       "      <td>5.000000</td>\n",
       "      <td>5.000000</td>\n",
       "      <td>5.0</td>\n",
       "      <td>5.000000</td>\n",
       "      <td>5.0</td>\n",
       "      <td>0</td>\n",
       "      <td>5.000000</td>\n",
       "      <td>5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>unique</th>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>0</td>\n",
       "      <td>NaN</td>\n",
       "      <td>5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>top</th>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>c7128691-de05-41f4-8ffa-ddd12a640ba9</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>freq</th>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>mean</th>\n",
       "      <td>0.800000</td>\n",
       "      <td>0.119282</td>\n",
       "      <td>1.0</td>\n",
       "      <td>0.820000</td>\n",
       "      <td>1.0</td>\n",
       "      <td>NaN</td>\n",
       "      <td>7.655640</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>std</th>\n",
       "      <td>0.447214</td>\n",
       "      <td>0.080145</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.216795</td>\n",
       "      <td>0.0</td>\n",
       "      <td>NaN</td>\n",
       "      <td>2.665656</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>min</th>\n",
       "      <td>0.000000</td>\n",
       "      <td>0.043368</td>\n",
       "      <td>1.0</td>\n",
       "      <td>0.500000</td>\n",
       "      <td>1.0</td>\n",
       "      <td>NaN</td>\n",
       "      <td>5.409900</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>25%</th>\n",
       "      <td>1.000000</td>\n",
       "      <td>0.053311</td>\n",
       "      <td>1.0</td>\n",
       "      <td>0.700000</td>\n",
       "      <td>1.0</td>\n",
       "      <td>NaN</td>\n",
       "      <td>5.633545</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>50%</th>\n",
       "      <td>1.000000</td>\n",
       "      <td>0.107826</td>\n",
       "      <td>1.0</td>\n",
       "      <td>0.900000</td>\n",
       "      <td>1.0</td>\n",
       "      <td>NaN</td>\n",
       "      <td>6.451075</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>75%</th>\n",
       "      <td>1.000000</td>\n",
       "      <td>0.153003</td>\n",
       "      <td>1.0</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>1.0</td>\n",
       "      <td>NaN</td>\n",
       "      <td>9.194739</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>max</th>\n",
       "      <td>1.000000</td>\n",
       "      <td>0.238903</td>\n",
       "      <td>1.0</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>1.0</td>\n",
       "      <td>NaN</td>\n",
       "      <td>11.588943</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "        feedback.correctness  feedback.embedding_cosine_distance  \\\n",
       "count               5.000000                            5.000000   \n",
       "unique                   NaN                                 NaN   \n",
       "top                      NaN                                 NaN   \n",
       "freq                     NaN                                 NaN   \n",
       "mean                0.800000                            0.119282   \n",
       "std                 0.447214                            0.080145   \n",
       "min                 0.000000                            0.043368   \n",
       "25%                 1.000000                            0.053311   \n",
       "50%                 1.000000                            0.107826   \n",
       "75%                 1.000000                            0.153003   \n",
       "max                 1.000000                            0.238903   \n",
       "\n",
       "        feedback.helpfulness  feedback.score_string:accuracy  \\\n",
       "count                    5.0                        5.000000   \n",
       "unique                   NaN                             NaN   \n",
       "top                      NaN                             NaN   \n",
       "freq                     NaN                             NaN   \n",
       "mean                     1.0                        0.820000   \n",
       "std                      0.0                        0.216795   \n",
       "min                      1.0                        0.500000   \n",
       "25%                      1.0                        0.700000   \n",
       "50%                      1.0                        0.900000   \n",
       "75%                      1.0                        1.000000   \n",
       "max                      1.0                        1.000000   \n",
       "\n",
       "        feedback.not_uncertain error  execution_time  \\\n",
       "count                      5.0     0        5.000000   \n",
       "unique                     NaN     0             NaN   \n",
       "top                        NaN   NaN             NaN   \n",
       "freq                       NaN   NaN             NaN   \n",
       "mean                       1.0   NaN        7.655640   \n",
       "std                        0.0   NaN        2.665656   \n",
       "min                        1.0   NaN        5.409900   \n",
       "25%                        1.0   NaN        5.633545   \n",
       "50%                        1.0   NaN        6.451075   \n",
       "75%                        1.0   NaN        9.194739   \n",
       "max                        1.0   NaN       11.588943   \n",
       "\n",
       "                                      run_id  \n",
       "count                                      5  \n",
       "unique                                     5  \n",
       "top     c7128691-de05-41f4-8ffa-ddd12a640ba9  \n",
       "freq                                       1  \n",
       "mean                                     NaN  \n",
       "std                                      NaN  \n",
       "min                                      NaN  \n",
       "25%                                      NaN  \n",
       "50%                                      NaN  \n",
       "75%                                      NaN  \n",
       "max                                      NaN  "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "candidate_prompt = hub.pull(\"wfh/langsmith-agent-prompt:39f3bbd0\")\n",
    "\n",
    "chain_results = run_on_dataset(\n",
    "    dataset_name=dataset_name,\n",
    "    llm_or_chain_factory=functools.partial(\n",
    "        create_agent, prompt=candidate_prompt, llm_with_tools=llm_with_tools\n",
    "    ),\n",
    "    evaluation=evaluation_config,\n",
    "    verbose=True,\n",
    "    client=client,\n",
    "    project_name=f\"runnable-agent-test-39f3bbd0-{unique_id}\",\n",
    "    project_metadata={\n",
    "        \"env\": \"testing-notebook\",\n",
    "        \"model\": \"gpt-3.5-turbo\",\n",
    "        \"prompt\": \"39f3bbd0\",\n",
    "    },\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9fafd1dd-debf-4256-a609-a6b3a7c52c49",
   "metadata": {},
   "source": [
    "## Exporting datasets and runs\n",
    "\n",
    "LangSmith lets you export data to common formats such as CSV or JSONL directly in the web app. You can also use the client to fetch runs for further analysis, to store in your own database, or to share with others. Let's fetch the run traces from the evaluation run.\n",
    "\n",
    "**Note: It may be a few moments before all the runs are accessible.**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "33bfefde-d1bb-4f50-9f7a-fd572ee76820",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "runs = client.list_runs(project_name=chain_results[\"project_name\"], execution_order=1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "id": "6595c888-1f5c-4ae3-9390-0a559f5575d1",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'correctness': {'n': 5, 'avg': 0.8},\n",
       " 'embedding_cosine_distance': {'n': 5, 'avg': 0.11926},\n",
       " 'helpfulness': {'n': 5, 'avg': 1.0},\n",
       " 'not_uncertain': {'n': 5, 'avg': 1.0},\n",
       " 'score_string:accuracy': {'n': 5, 'avg': 0.82}}"
      ]
     },
     "execution_count": 38,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# After some time, these will be populated.\n",
    "client.read_project(project_name=chain_results[\"project_name\"]).feedback_stats"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2646f0fb-81d4-43ce-8a9b-54b8e19841e2",
   "metadata": {
    "tags": []
   },
   "source": [
    "## Conclusion\n",
    "\n",
    "Congratulations! You have successfully traced and evaluated an agent using LangSmith!\n",
    "\n",
    "This was a quick guide to get started, but there are many more ways to use LangSmith to speed up your developer flow and produce better results.\n",
    "\n",
    "For more information on how you can get the most out of LangSmith, check out [LangSmith documentation](https://docs.smith.langchain.com/), and please reach out with questions, feature requests, or feedback at [support@langchain.dev](mailto:support@langchain.dev)."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "poetry-venv",
   "language": "python",
   "name": "poetry-venv"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
